package com.nbcb.fund.common.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linqiankun
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class OriginFilter implements Filter {

    public OriginFilter() {
    }


    @Override
    public void init(FilterConfig filterConfig) {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (isCorsRequest((HttpServletRequest) request)) {
            HttpServletRequest servletRequest = (HttpServletRequest) request;
            HttpServletResponse servletResponse = (HttpServletResponse) response;
            servletResponse.setHeader("Access-Control-Allow-Origin", servletRequest.getHeader("Origin"));
            servletResponse.setHeader("Access-Control-Allow-Methods", servletRequest.getHeader("Access-Control-Request-Method"));
            servletResponse.setHeader("Access-Control-Allow-Headers", servletRequest.getHeader("Access-Control-Request-Headers"));
            servletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            servletResponse.setHeader("Access-Control-Max-Age", this.getCorsMaxAge());
        }

        if (!isPreFlightRequest(request)) {
            chain.doFilter(request, response);
        } else {
            return;
        }
    }

    private static boolean isCorsRequest(HttpServletRequest request) {
        return request.getHeader("Origin") != null;
    }

    private static boolean isPreFlightRequest(ServletRequest servletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        return isCorsRequest(request) && "OPTIONS".equalsIgnoreCase(request.getMethod()) && request.getHeader("Access-Control-Request-Method") != null;
    }

    private String getCorsMaxAge() {
        return "86400";
    }

    @Override
    public void destroy() {
    }
}